//
//  main.cpp
//  
//
//  Created by Kun Zhao on 13/03/07.
//  Copyright (c) 2013 Kyoto University. All rights reserved.
//

#include <iostream>
#include <fstream>
#include <kvs/StructuredVolumeObject>
#include <kvs/StructuredVolumeImporter>
#include "WriteStructuredVolume.h"

using namespace std;

int main( int argc, char** argv )
{
    kvs::StructuredVolumeObject* object = new kvs::StructuredVolumeImporter( "../../Data/speel/speel.kvsml" );
    float* pvalues = (float*)object->values().pointer();
    size_t nx_ori = object->resolution().x();
    size_t ny_ori = object->resolution().y();
    size_t nz_ori = object->resolution().z();
    size_t nx = nx_ori;
    size_t ny = ny_ori;
    size_t nz = 100;
    
    ifstream infile( "depth.txt" );    
    float* index = new float[78];
    float* depth = new float[78];
    float* dz = new float[78];
    for ( size_t i = 0; i < 78; i ++ )
    {
        infile >> index[i];
        infile >> depth[i];
        infile >> dz[i];
    }
    
    float ocean_depth[ nx_ori * ny_ori ];
    for ( size_t j = 0; j < ny_ori; j++ )
    {
        for ( size_t i = 0; i < nx_ori; i++ )
        {
            size_t oindex = i + j * nx_ori;
            ocean_depth[oindex] = 2.0;
            for ( size_t k = 0; k < nz_ori; k++ )
            {
                size_t index = i + j * nx_ori + k * nx_ori * ny_ori;
                if( pvalues[index] > 31 ) 
                {
                    if( k != nz_ori - 1 )
                    {
                        ocean_depth[oindex] = depth[nz_ori - 2 - k];
                        break;
                    }
                }
            }
        }
    }
    
    // create 0-1 ref volume
    kvs::AnyValueArray values;
    unsigned char* buf = static_cast<unsigned char*>( values.allocate<unsigned char>( nx * ny * nz ) );
    
    for ( size_t k = 0; k < nz; k ++ )
        for ( size_t j = 0; j < ny; j ++ )
            for ( size_t i = 0; i < nx; i ++ )
            {
                size_t index = i + j * nx + k * nx * ny;
                size_t oindex = i + j * nx;
                float depth_new = 477.0 - k * 5.0;
                if ( depth_new > ocean_depth[oindex] )
                    buf[index] = 0;
                else buf[index] = 1;
            }

    kvs::Vector3ui resolution( nx, ny, nz );
    kvs::VolumeObjectBase::GridType grid_type = kvs::VolumeObjectBase::Uniform;
    kvs::StructuredVolumeObject* t_object = new kvs::StructuredVolumeObject();
    t_object->setGridType( grid_type);
    t_object->setVeclen( 1 );
    t_object->setResolution( resolution );
    t_object->setValues( values );
    
    t_object->updateMinMaxCoords();
    t_object->updateMinMaxValues();
    
    WriteStructuredVolume( t_object, "ref.kvsml" );
    
}
